﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;
using CXMLStudioIDE.BusinessLayer;
using CXMLStudioIDE.Common;
using CXMLStudioIDE.Common.Entities;
using CXMLStudioIDE.DataAccessLayer;
using CXMLStudioIDE.Presenters;
using CXMLStudioIDE.Views;
using CXMLStudioIDE.WinFormsUI.CXMLStudioControls;
using CXMLStudioIDE.WinFormsUI.Docking;
using System.IO;
using System.Xml;

namespace CXMLStudioIDE.Forms
{
    public partial class GoldEntryForm : DockContent, IGoldEntryView
    {
        #region Declarations

        private readonly PropertyReflector m_propertyreflector;
        private readonly PropertiesBL propBL;
        private PropertiesDAL _PropDal;
        private SortedList control_tops;
        private BindingSource m_bindingsource;
        private Form m_goldform;
        private GoldEntryPresenter m_presenter;

        #endregion

        #region Events

        public delegate void OnFormCompletedEventHandler(object sender);
        public delegate void OnGoldFormLoadingEventHandler(object sender);
        public delegate void OnInstanceAddedEventHandler(object sender);
        public delegate void OnFileSelectedEventHandler(object sender, string filename);

        #endregion

        #region WorkerThread delegates

        #region Nested type: AddControlsDelegate

        private delegate bool AddControlsDelegate(DictionaryEntry entry);

        #endregion

        #region Nested type: InitProgressBarDelegate

        private delegate void InitProgressBarDelegate(int count);

        #endregion

        #region Nested type: PerformStepDelegate

        private delegate void PerformStepDelegate();

        #endregion

        #region Nested type: ResumeLayoutDelegate

        private delegate void ResumeLayoutDelegate(int nodecount);

        #endregion

        #region Nested type: SetTabIndexesDelegate

        private delegate void SetTabIndexesDelegate();

        #endregion

        #region Nested type: SuspendLayoutDelegate

        private delegate void SuspendLayoutDelegate();

        #endregion

        #region Nested type: SuspendLayoutDelegate

        private delegate void NoControlsAddedMessageDelegate();

        #endregion

        #endregion

        #region Constructors
        public GoldEntryForm(MainForm parent, CXMLTreeNode rootNode, AddInstanceArgs addInstanceArgs):this(parent,rootNode)
        {
            CallingGoldForm = addInstanceArgs.CallingGoldForm;
            CallingCXMLNode = addInstanceArgs.CallingNode;
            AddInstanceMode = addInstanceArgs.Mode;
            IsInstanceToAdd = true;
            btn_AddInstance.Visible = true;
            btn_AddInstance.Enabled = false;
        }

        public GoldEntryForm(MainForm parent, CXMLTreeNode rootNode)
        {
            xml_SerializedEntity = null;
            AddedCXMLNode = null;
            RootCXMLNode = null;
            EntityType = null;
            EntityInstance = null;
            RootBusinessEntity = null;
            ParentMainForm = parent;
            InitializeComponent();
            InitGoldForm();
            IsInstanceToAdd = false;
            AutoScroll = true;
            btn_SaveInstance.Enabled = false;
            btn_LoadInstance.Enabled = false;
            btn_InstancePreview.Enabled = false;
            cmb_EntityInstances.Enabled = false;
            propBL = new PropertiesBL();
            _PropDal = new PropertiesDAL();
            m_propertyreflector = new PropertyReflector();
            m_presenter = new GoldEntryPresenter(this);
            FormClosing += OnFormClosing;
            btn_SaveInstance.Click += OnSaveInstanceClicked;
            btn_InstancePreview.Click += OnInstancePreviewClicked;
            btn_LoadInstance.Click += OnLoadInstanceClicked;
            btn_AddInstance.Click += OnAddToParentClicked;
            if (rootNode != null)
            {
                RootCXMLNode = rootNode;
            }
        }

        #endregion

        #region IGoldEntryView Members

        public void EnableAddInstanceButton()
        {
            btn_AddInstance.Enabled = true;
        }

        /* Highlights the control corresponding to TreeView synchronization */

        public void SelectByLineage(string lineage, bool setfocus)
        {
            foreach (Control c in m_goldform.Controls)
            {
                if (c.Name.StartsWith("lbl_"))
                {
                    c.BackColor = Color.Transparent;
                    if (c.Name.Equals("lbl_" + lineage))
                    {
                        c.BackColor = Color.PowderBlue;
                        m_goldform.ScrollControlIntoView(c);
                    }
                }
                if (c.Name.Equals("txt_" + lineage) && setfocus)
                {
                    var txt = c as TextBox;
                    if (c != null)
                    {
                        txt.Focus();
                        txt.Select();
                    }
                }
            }
        }

        public string GetValueByBindingName(object instance, string BindingName)
        {
            if (instance != null && !string.IsNullOrEmpty(BindingName))
            {
                object value = m_propertyreflector.GetValue(instance, BindingName);
                if (value != null)
                    return value.ToString();
            }
            return null;
        }

        public string GetValueByLineage(string lineage)
        {
            foreach (Control c in m_goldform.Controls)
            {
                if (c.Name.Equals("txt_" + lineage))
                {
                    return c.Text;
                }
            }
            return null;
        }

        public void LoadGoldForm(CXMLTreeNode node)
        {
            if (CallingGoldForm != null && node.BindingName != null)
            {
                EntityType = CallingGoldForm.EntityType.Assembly.GetType(node.BindingName);
                EntityInstance = Activator.CreateInstance(EntityType);
            }
            else
            {
                EntityInstance = Activator.CreateInstance(node.EntityType);
                EntityType = node.EntityType;
            }
            btn_SaveInstance.Enabled = true;
            btn_LoadInstance.Enabled = true;
            btn_InstancePreview.Enabled = true;
            cmb_EntityInstances.Enabled = true;

            if (EntityInstance != null)
            {
                components = new Container();
                m_bindingsource = new BindingSource(node.EntityType, "");
                //m_bindingsource = new System.Windows.Forms.BindingSource(this.components);
                //m_bindingsource = new System.Windows.Forms.BindingSource();
                //m_bindingsource = new System.Windows.Forms.BindingSource(m_instance,"");
                //m_bindingsource.DataSource = m_instance;
                m_goldform.Text = node.Name;
                if (node != null && node.BusinessEntity != null)
                {
                    LoadInstanceCombo(node.BusinessEntity.ID);
                    RootBusinessEntity = node.BusinessEntity;
                    lbl_EntityName.Text = node.BusinessEntity.Name;
                    lbl_ContextTxt.Text = node.BusinessEntity.EntityType.EntityTypeContextName;
                    lbl_EntityVersionTxt.Text = node.BusinessEntity.EntityVersion.FullVersion;
                    if (node.BusinessEntity.ParentProject != null)
                    {
                        lbl_ProjectScopeTxt.Text = node.BusinessEntity.ParentProject.Scope.Name;
                        Project p = node.BusinessEntity.ParentProject;
                        groupBox1.Text = "Project: " + p.Name;
                        lbl_ProjectScopeTxt.Text = p.Scope.Name;
                        lbl_ProjectContextTxt.Text = p.Context.Name;
                    }
                    OnGoldFormLoading(this);
                }
            }
            StartAddControlsToFormWorker(node);
        }

        public void ReleaseBindings()
        {
            try
            {
                if (EntityType != null && m_bindingsource != null)
                {
                    m_bindingsource.DataSource = EntityType;
                    m_bindingsource.DataMember = "";
                }
            }
            catch (Exception ex)
            {
                //IGNORE FOR NOW
            }
        }

        public void AddInstance(object objToAdd, string listpropertyname, CXMLTreeNode addednode)
        {
            try
            {
                AddedCXMLNode = addednode;
                var pr = new PropertyReflector();
                object placelist = pr.GetValue(EntityInstance, listpropertyname);
                MethodInfo mi = placelist.GetType().GetMethod("Add");
                var parms = new[] {objToAdd};
                mi.Invoke(placelist, parms);
                OnInstanceAdded(this);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "GoldEntryForm.AddInstance Exception:" + ex.Message + "\n" +
                                      ex.StackTrace, "CXMLStudioIDE", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        private void InitGoldForm()
        {
            m_goldform = new Form();
            m_goldform.Name = "Form1";
            m_goldform.Text = "Form1";
            m_goldform.AllowDrop = true;
            //m_goldform.AutoSize = true;
            m_goldform.AutoScroll = true;
            m_goldform.Location = new Point(10, 10);
            m_goldform.Size = new Size(500, 500);
            m_goldform.MaximumSize = new Size(0, 0);
            m_goldform.TopLevel = false;
            //m_goldform.Dock = DockStyle.Fill;
            //m_goldform.AutoScaleMode = AutoScaleMode.Dpi;
            m_goldform.DragDrop += GoldEntryForm_DragDrop;
            m_goldform.DragEnter += GoldEntryForm_DragEnter;
            m_goldform.MaximizeBox = false;
            m_goldform.MinimizeBox = false;
            m_goldform.ControlBox = false;
            m_goldform.Show();
            pnl_GoldEntryForm.AutoScroll = true;
            pnl_GoldEntryForm.Height = Convert.ToInt32(Screen.GetBounds(this).Height*0.7);
            m_goldform.Height = Convert.ToInt32(Screen.GetBounds(this).Height*0.60);
            m_goldform.Width = Convert.ToInt32(Screen.GetBounds(this).Width*0.60);
            pnl_GoldOptions.Width = Screen.GetBounds(this).Width;
            pnl_GoldEntryForm.Controls.Add(m_goldform);
            Refresh();
        }

        private object CloneObject(object o)
        {
            Type t = o.GetType();
            PropertyInfo[] properties = t.GetProperties();

            Object p = t.InvokeMember("", BindingFlags.CreateInstance, null, o, null);

            foreach (PropertyInfo pi in properties)
            {
                if (pi.CanWrite)
                {
                    pi.SetValue(p, pi.GetValue(o, null), null);
                }
            }

            return p;
        }

        private object GetSampleInstance(Type t_BusinessEntityType)
        {
            Object instance = Activator.CreateInstance(t_BusinessEntityType);
            //t_BusinessEntityType.InvokeMember("Address1", BindingFlags.SetField,null, instance, new object[] { "Arbor Circle" },null);

            FieldInfo[] MyFields = t_BusinessEntityType.GetFields(BindingFlags.Public | BindingFlags.Instance);
            for (int i = 0; i < MyFields.Length; i++)
            {
                Debug.WriteLine("Field:" + MyFields[i].Name);
            }
            return instance;
        }

        private void GoldEntryForm_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(typeof (CXMLTreeNode)))
                e.Effect = DragDropEffects.Copy;
            else
                e.Effect = DragDropEffects.None;
        }

        private void GoldEntryForm_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(typeof (CXMLTreeNode)))
            {
                var node = (CXMLTreeNode) e.Data.GetData(typeof (CXMLTreeNode));
                if (node != null)
                {
                    LoadGoldForm(node);
                }
            }
        }

        private void StartAddControlsToFormWorker(CXMLTreeNode node)
        {
            if (node != null && node.Level == 0)
            {
                Text = node.Text;
                Text = "Gold Entry Form - " + node.Text;
                if (node.BusinessEntity != null && node.BusinessEntity.ControlBindings != null)
                {
                    backgroundWorker1.RunWorkerAsync(node.BusinessEntity.ControlBindings);
                }
            }
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                var controlbindings = e.Argument as Hashtable;
                bool b_ControlAdded = false;
                int Cont = 0;

                AddControlsDelegate acd = AddControls;
                InitProgressBarDelegate ipbd = InitProgressBar;
                Invoke(ipbd, controlbindings.Count);
                SuspendLayoutDelegate sld = MySuspendLayout;
                Invoke(sld);
                PerformStepDelegate psd = PerformStep;

                foreach (DictionaryEntry de in controlbindings)
                {
                    b_ControlAdded = (bool) Invoke(acd, de);
                    if (b_ControlAdded)
                    {
                        Cont++;
                    }
                    Invoke(psd);
                }

                ResumeLayoutDelegate rld = MyResumeLayout;
                Invoke(rld, controlbindings.Count);

                SetTabIndexesDelegate stid = SetTabIndexes;
                Invoke(stid);
                if (Cont == 0)
                {
                    NoControlsAddedMessageDelegate ncamd = NoControlsAdded;
                    Invoke(ncamd);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void NoControlsAdded()
        {
            MessageBox.Show(this, "This form has not been created yet..Please contact the administrator" +
            "\nEntity: [" + RootBusinessEntity.Name + "] Context:[" + RootBusinessEntity.EntityType.EntityTypeContextName +
            "] Version:[" + RootBusinessEntity.EntityVersion.FullVersion + "]",
                            "CXMLStudio", MessageBoxButtons.OK,
                            MessageBoxIcon.Exclamation);
        }

        public bool AddControls(DictionaryEntry entry)
        {
            Control ctrl = null;
            Label lbl = null;
            var lineage = (string) entry.Key;
            var bindingname = (string) entry.Value;
            string labeltext = null;
            Binding binding = null;
            string prefix = null;

            try
            {
                //labeltext = (bindingname.Contains(".") ? bindingname.Substring(bindingname.IndexOf('.') + 1) : bindingname);
                labeltext = Common.Common.GetLabelNameFromBindingName(bindingname);
                int i_EntityTypeVersionID = Common.Common.GetEntityTypeVersionIDFromControlName(lineage);
                if (i_EntityTypeVersionID > 0)
                {
                    ctrl =
                        propBL.GetControlFromBinary(i_EntityTypeVersionID, lineage, DisplayContext.FormDesigner,
                                                    ControlType.Control) as Control;
                    if (ctrl != null)
                    {
                        /** Set the data bindings for TextBoxes **/
                        if (ctrl.Name.Contains("_"))
                        {
                            prefix = ctrl.Name.Substring(0, ctrl.Name.IndexOf('_'));
                            if (prefix != null)
                            {
                                //Debug.WriteLine(labeltext + " - " + bindingname);
                                switch (prefix)
                                {
                                    case "txt":

                                        #region Test create instance

                                        //if(bindingname.Equals("StateOrProvince.StateOrProvinceName"))
                                        //{
                                        //    PropertyInfo[] properties = _EntityType.GetProperties(); //returns all publicproperties
                                        //    foreach (PropertyInfo property in properties)
                                        //    {
                                        //        if(property.Name.Equals("StateOrProvince"))
                                        //        {
                                        //            Type t = property.PropertyType;
                                        //            object m_stateinstance = Activator.CreateInstance(t);
                                        //        }
                                        //    }
                                        //}

                                        #endregion

                                        if (!bindingname.Contains("Item"))
                                        {
                                            binding = ctrl.DataBindings.Add("Text", m_bindingsource, bindingname, true);
                                            binding.BindingComplete += BindingComplete;
                                        }
                                        break;
                                    case "dtp":
                                        if (!bindingname.Contains("Item"))
                                        {
                                            binding = ctrl.DataBindings.Add("Value", m_bindingsource, bindingname, true);
                                            binding.BindingComplete += BindingComplete;
                                        }
                                        break;
                                    case "chk":
                                        if (!bindingname.Contains("Item"))
                                        {
                                            binding = ctrl.DataBindings.Add("Checked", m_bindingsource, bindingname,
                                                                            true);
                                        }
                                        break;
                                    case "cmb":
                                        break;
                                }
                            }
                        }
                        /** Create corresponding label **/
                        lbl = new Label();
                        lbl.Name = "lbl_" + lineage;
                        lbl.Text = labeltext;
                        lbl.Top = ctrl.Top;
                        lbl.Width = 150;
                        lbl.Left = ctrl.Left - 160;
                        control_tops.Add(ctrl.Top, ctrl);
                        m_goldform.Controls.Add(lbl);
                        m_goldform.Controls.Add(ctrl);
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                //    MessageBox.Show(ex.Message);
                Debug.WriteLine("Exception:" + ex.Message);
            }
            return false;
        }

        // Handle the BindingComplete event to catch errors and exceptions 
        // in binding process.
        private void BindingComplete(object sender,
                                     BindingCompleteEventArgs e)
        {
            if (e.BindingCompleteState != BindingCompleteState.Success)
            {
                //MessageBox.Show("Binding: " + e.ErrorText);
            }
        }

        private void btn_ClearAll_Click(object sender, EventArgs e)
        {
            ClearAllFields();
        }

        private void GoldEntryForm_FormClosing(object sender, FormClosingEventArgs e)
        {
        }

        #region Worker Event implementations

        private void SetTabIndexes()
        {
            /* Set the correct TabIndexes */
            for (int j = 0; j < control_tops.Count; j++)
            {
                var c = control_tops.GetByIndex(j) as Control;
                if (c != null)
                    c.TabIndex = j;
            }
        }

        private void InitProgressBar(int count)
        {
            //Initialize Progress Bar
            progressBar1.Maximum = count;
            progressBar1.Step = 1;
            lblProgress.Text = "Opening Form Please Wait...";
            pnl_Progress.Visible = true;
            pnl_Progress.Refresh();
            control_tops = new SortedList(count);
        }

        private void MySuspendLayout()
        {
            m_goldform.SuspendLayout();
            DrawingControl.SuspendDrawing(m_goldform);
        }

        private void MyResumeLayout(int nodecount)
        {
            lblProgress.Text = lblProgress.Text + "...Done!";
            pnl_Progress.Update();

            DrawingControl.ResumeDrawing(m_goldform);
            m_goldform.ResumeLayout(true);
            if (nodecount > 20)
            {
                Thread.Sleep(700);
                pnl_Progress.Visible = false;
                //pnl_GoldEntryForm.Height = m_goldform.Height;
            }
            //m_goldform.WindowState = FormWindowState.Maximized;
            OnGoldFormCompleted(this);
            try
            {
                m_bindingsource.DataSource = EntityInstance;
            }
            catch (Exception ex)
            {
            }
        }

        private void PerformStep()
        {
            progressBar1.PerformStep();
        }

        #endregion

        #region OldLoadFromFile

        //private void LoadFormFromFile()
        //{
        //    // Create Form
        //    BasicHostLoader bhl = new BasicHostLoader(m_filename);
        //    ServiceContainer newservicecontainer = new ServiceContainer();
        //    IDesignerHost newhost = new CXMLStudioIDE.DesignerHost.DesignerHost(newservicecontainer);
        //    ((CXMLStudioIDE.DesignerHost.DesignerHost)newhost).BeginLoad(bhl);
        //    Form newForm = newhost.RootComponent as Form;
        //    this.TopLevel = true;
        //    this.Refresh();
        //    TextBox txt = null;
        //    Label lbl = null;

        //    try
        //    {
        //        int Top = 0;
        //        int Left = 0;
        //        int Width = 0;

        //        BusinessEntityBuilder beb = new BusinessEntityBuilder();
        //        BusinessEntityCollection bec = m_parent.m_SolutionManager.m_solution.GetBusinessEntitiesInSolution();
        //        BusinessEntity be = bec.GetBusinessEntityByTreeViewID(m_parent.m_SolutionManager.m_solution.Projects[0].Entities[0].TreeViewID);

        //        //Type t_BusinessEntityType = beb.GetBusinessEntityType(be);
        //        //m_instance = (Object)Activator.CreateInstance(t_BusinessEntityType);

        //        m_instance = new Enterprise.PlaceType();
        //        this.components = new System.ComponentModel.Container();
        //        m_bindingsource = new System.Windows.Forms.BindingSource(this.components);
        //        m_bindingsource.DataSource = m_instance;

        //        int count = 0;

        //        ((System.ComponentModel.ISupportInitialize)(m_bindingsource)).BeginInit();

        //        foreach (Control c in newForm.Controls)
        //        {
        //            //Debug.WriteLine("Component name:" + ((Control)c).Name + " DesignMode:" + c.Site.DesignMode);
        //            switch (c.GetType().Name)
        //            {
        //                case "TextBox":
        //                    txt = new TextBox();
        //                    txt.Name = c.Name;
        //                    txt.Location = c.Location;
        //                    txt.Size = c.Size;
        //                    txt.TabIndex = c.TabIndex;
        //                    string suffix = txt.Name.Substring(txt.Name.IndexOf('_') + 1);
        //                    object o = null;
        //                    o = be.ControlBindings[suffix];
        //                    if (o != null)
        //                    {
        //                        txt.DataBindings.Add(new Binding("Text", m_bindingsource, o.ToString(), true));
        //                        Debug.WriteLine("Adding binding:" + o.ToString() + " Databinding count:" + txt.DataBindings.Count);
        //                    }
        //                    this.Controls.Add(txt);
        //                    break;
        //                case "Label":
        //                    lbl = new Label();
        //                    lbl.Name = c.Name;
        //                    lbl.Text = c.Text;
        //                    lbl.Location = c.Location;
        //                    lbl.Size = c.Size;
        //                    lbl.TabIndex = c.TabIndex;
        //                    this.Controls.Add(lbl);
        //                    break;
        //            }
        //            Top = c.Top;
        //            Left = c.Left;
        //            Width = c.Width;
        //            count++;
        //        }
        //        Button b = new Button();
        //        b.Text = "Submit";
        //        b.Top = Top + 50;
        //        b.Left = Left + 100;
        //        b.Width = Width;
        //        b.Click += new EventHandler(OnSubmit);
        //        this.Controls.Add(b);
        //        ((System.ComponentModel.ISupportInitialize)(m_bindingsource)).EndInit();
        //    }
        //    catch (Exception e)
        //    {
        //        MessageBox.Show(e.Message);
        //    }

        //    //this.ResumeLayout();
        //    this.Refresh();
        //}

        #endregion

        #region public Properties

        public int EntityID
        {
            get { return RootBusinessEntity.ID; }
        }

        public MainForm ParentMainForm { get; set; }
        public BusinessEntity RootBusinessEntity { get; set; }
        public string xml_SerializedEntity { get; set; }
        public object EntityInstance { get; set; }
        public Type EntityType { get; set; }

        public object SelectedItem
        {
            get { return cmb_EntityInstances.SelectedItem; }
        }

        public CXMLTreeNode RootCXMLNode { get; set; }
        public bool IsInstanceToAdd { get; set; }
        public GoldEntryForm CallingGoldForm { get; set; }
        public CXMLTreeNode CallingCXMLNode { get; set; }
        public CXMLTreeNode AddedCXMLNode { get; set; }
        public string EntityInstanceDescription { get; set; }
        public AddInstanceForm.AddInstanceMode AddInstanceMode { get; set; }

        #endregion

        #region events

        public new event FormClosingEventHandler OnFormClosing;
        public event EventHandler OnInstancePreviewClicked;
        public event EventHandler OnSaveInstanceClicked;
        public event EventHandler OnLoadInstanceClicked;
        public event EventHandler OnAddToParentClicked;
        public event OnFormCompletedEventHandler OnGoldFormCompleted;

        public event OnGoldFormLoadingEventHandler OnGoldFormLoading;
        public event OnInstanceAddedEventHandler OnInstanceAdded;
        public event OnFileSelectedEventHandler OnFileSelected;


        #endregion

        #region Methods

        public void SetBindingSource()
        {
            if (EntityInstance != null)
            {
                m_bindingsource.DataSource = EntityInstance;
            }
        }

        public void LoadInstanceCombo(int EntityID)
        {
            var dal = new CXMLStudioDAL();
            dsEntityInstance = dal.GetEntityInstances(EntityID);
            if (dsEntityInstance.Tables.Count > 0)
            {
                cmb_EntityInstances.ValueMember = dsEntityInstance.Tables[0].Columns[0].ColumnName;
                cmb_EntityInstances.DisplayMember = dsEntityInstance.Tables[0].Columns[1].ColumnName;
                cmb_EntityInstances.DataSource = dsEntityInstance.Tables[0];
            }
        }
        public void ClearAllFields()
        {
            foreach (Control c in m_goldform.Controls)
            {
                switch (c.GetType().Name)
                {
                    case "TextBox":
                        c.Text = "";
                        break;
                    case "CheckBox":
                        ((CheckBox)c).Checked = false;
                        break;
                    case "ComboBox":
                        ((ComboBox)c).SelectedIndex = -1;
                        break;
                }
            }
        }

        #endregion

        private void clearallToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ClearAllFields();
        }

        private void loadFromFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string fileName = null;
            // Open File Dialog
            var dlg = new OpenFileDialog();
            dlg.DefaultExt = "xml";
            dlg.Filter = "Xml Files|*.xml";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                fileName = dlg.FileName;
                OnFileSelected(this, fileName);
            }

            if (fileName == null)
                return;
        }
    }
}